﻿using Infrastructure.RestSharpWrap;
using RestSharp;

namespace Domain.Repository
{
    public class BaseRepository
    {
        protected readonly IRestClientExt _restClient;

        public BaseRepository(IRestClientExt restClient)
        {
            _restClient = restClient ?? throw new ArgumentNullException(nameof(restClient));
        }

        protected async Task<TResponse> Request<TResponse, TRequest>(string method, TRequest model) where TRequest : class
        {
            var request = new RestRequest(method)
                .AddJsonBody(model);

            var response = await _restClient
                .PostAsync<ResponseModel<TResponse>>(request);

            if (response.IsSuccessful)
            {
                return response.Data;
            }

            throw new InvalidOperationException("数据获取失败");
        }

        protected async Task<TResponse> Request<TResponse, TRequest>(string method, TRequest model, Func<dynamic, TResponse> func) where TRequest : class
        {
            var request = new RestRequest(method)
                .AddJsonBody(model);

            var response = await _restClient
                .PostAsync<ResponseModel<dynamic>>(request);

            if (response.IsSuccessful)
            {
                return func(response.Data);
            }

            throw new InvalidOperationException("数据获取失败");
        }
    }
}
